package sort;

/**
 * @author LQQ
 * @version V1.0
 * @Package PACKAGE_NAME
 * @date 2020/10/11 16:19
 * @Description
 */
public class InsertionSort {
    public static int[] insertionSort(int[] array) {
        if (array.length == 0) return array;
        for (int i = 1; i < array.length; i++) {
            int temp = array[i];
            int index = i;
            for (int j = i - 1; j >= 0; j--) {
                if (array[j] > temp) {
                    // 记录插值的位置
                    index = j;
                    array[j + 1] = array[j];
                } else break;
            }
            if (index != i) array[index] = temp;
        }
        return array;
    }


    public static void main(String[] args) {
        int[] array = new int[]{11, 1, 3, 1, 4, 7, 45, 76, 23, 7, 34, 9, 90, 0};
        array = insertionSort(array);
        for (int num : array) {
            System.out.println(num);
        }
    }

    // 用while做
    public static int[] insertionSort2(int[] array) {
        if (array.length == 0)
            return array;
        int current;
        for (int i = 0; i < array.length - 1; i++) {
            current = array[i + 1];
            int preIndex = i;
            while (preIndex >= 0 && current < array[preIndex]) {
                array[preIndex + 1] = array[preIndex];
                preIndex--;
            }
            array[preIndex + 1] = current;
        }
        return array;
    }

}
